<?php

class LoginForm extends Form
{
	public function LoginForm()
	{
		parent::__construct();
		
		$this->Name = 'login';
		$this->Title = translate('Login');
		$this->ButtonText = translate('Login');
		
		// add controls to section
		$this->Controls[] = a2o( 'FormControl', array( 'FieldName' => 'user', 'IsBound' => false, 'Title' => translate('User') ) );
		$this->Controls[] = a2o( 'FormControl', array( 'FieldName' => 'password', 'Title' => translate('Password'), 'IsBound' => false, 'Type' => 'password' ) );
		
		$this->Login( );
	}
	
	public function Login()
	{
		if(session('user')!='')
		{
			$this->Messages[] = 'Logged in as ' . session('user') . '.';
			$this->HideControls = true;
		}
		else
		{
			// load form success?
			if( $this->LoadPostData())
			{
				if( UserManager::Authenticate( $_POST['user'], $_POST['password'] ) )
				{
					session_start();
					// set session user
					$_SESSION['user'] = $_POST['user'];
					App::$Current->User = $_POST['user'];
					session_write_close();
					
					// success
					$this->HideControls = true;
					$this->Messages[] = translate('Successfully logged in.');
				}
				else
					$this->Messages[] = translate('Login failed.');
			}
		}		
	}
}
